package com.example.webmodule.config;

import cn.hutool.core.util.NumberUtil;
import com.example.webmodule.config.interceptor.HttpRetryInterceptor;
import com.example.webmodule.properties.OkHttpProperties;
import okhttp3.Cache;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.File;
import java.util.concurrent.TimeUnit;

@Configuration
public class WebConfig {

    @Autowired
    private OkHttpProperties okHttpProperties;

    @Bean
    public OkHttpClient okHttpClient() {
        File cacheDirectory = new File("C:\\git\\spring\\multi-plateform-module\\src\\main\\resources\\cache");
        int cacheSize = 10 * 1024 * 1024; // 10 MB
        Cache cache = new Cache(cacheDirectory, cacheSize);

        ConnectionPool connectionPool = new ConnectionPool(
                NumberUtil.parseInt(okHttpProperties.getConnectionPool().get("maxIdleConnections"), 5),
                NumberUtil.parseInt(okHttpProperties.getConnectionPool().get("keepAliveDuration"), 3),
                TimeUnit.MINUTES);

        return new OkHttpClient.Builder()
                .connectTimeout(NumberUtil.parseInt(okHttpProperties.getConnectTimeout(), 1), TimeUnit.SECONDS)
                .callTimeout(NumberUtil.parseInt(okHttpProperties.getCallTimeout(), 3), TimeUnit.SECONDS)
                .readTimeout(NumberUtil.parseInt(okHttpProperties.getReadTimeout(), 1), TimeUnit.SECONDS)
//                .cache(cache)
                .connectionPool(connectionPool)
                .addInterceptor(new HttpRetryInterceptor(okHttpProperties.getMaxRetries()))
                // .authenticator()// OkHttp 的 Authenticator 接口用于处理 HTTP 请求的身份验证（如 Basic Auth、Digest Auth 或 Bearer Token）。当服务器返回 401 Unauthorized 响应时，Authenticator 会被触发，允许你提供新的凭证并重试请求。
                .build();
    }
}
